using System.Data.Linq;
using System.Linq;
using Magiq.Delete;
using Magiq.Insert;
using Magiq.Update;

namespace Magiq.Sql {
  public class MagiqToSql : IMagiqProvider {
    private const string DataQueryAssemblyQualifiedName =
      "System.Data.Linq.DataQuery`1, System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

    public MagiqToSql() {
      DependentTablesUpdateStrategy = new NotSupportedDependentTablesUpdateStrategy();
    }

    public IDependentTablesUpdateStrategy DependentTablesUpdateStrategy { get; set; }

    #region IMagiqProvider Members

    public IUpdateProvider GetUpdateProvider() {
      return new MagiqToSqlUpdateProvider(DependentTablesUpdateStrategy);
    }

    public IDeleteProvider GetDeleteProvider() {
      return new MagiqToSqlDeleteProvider();
    }

    public IInsertProvider GetInsertProvider() {
      return new MagiqToSqlInsertProvider();
    }

    public bool Handles(IQueryable queryable) {
      var type = queryable.GetType();
      if (!type.IsGenericType)
        return false;

      var genericType = type.GetGenericTypeDefinition();
      return genericType.AssemblyQualifiedName == DataQueryAssemblyQualifiedName ||
             genericType == typeof (Table<>);
    }

    #endregion
  }
}